package com.fzt.system.service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fzt.system.domain.entity.SysRoleMenuEntity;
import com.fzt.system.mapper.SysRoleMenuMapper;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色菜单关联服务
 * </p>
 *
 * @author 非洲铜
 * @since 2022-12-12
 */
@Service
@AllArgsConstructor
public class SysRoleMenuService extends ServiceImpl<SysRoleMenuMapper, SysRoleMenuEntity> {
    private final SysRoleMenuMapper sysRoleMenuMapper;

    public void saveOrUpdate(Long roleId, List<Long> menuIdList) {
        List<Long> dbMenuIdList = getMenuIdList(roleId);

        // 传入的有，数据库中没有，需要新增
        Collection<Long> needInsertList = CollUtil.subtract(menuIdList, dbMenuIdList);
        if (CollUtil.isNotEmpty(needInsertList)) {
            List<SysRoleMenuEntity> sysRoleMenuEntities = needInsertList.stream().map(menuId -> {
                SysRoleMenuEntity entity = new SysRoleMenuEntity();
                entity.setRoleId(roleId);
                entity.setMenuId(menuId);
                return entity;
            }).collect(Collectors.toList());

            saveBatch(sysRoleMenuEntities);
        }

        // 数据库中有，传入的没有，需要删除
        Collection<Long> needRemoveList = CollUtil.subtract(dbMenuIdList, menuIdList);
        if (CollUtil.isNotEmpty(needRemoveList)) {
            remove(lambdaQuery()
                    .eq(SysRoleMenuEntity::getRoleId, roleId)
                    .in(SysRoleMenuEntity::getMenuId, needRemoveList));
        }
    }

    /**
     * 查询角色下关联的菜单ID列表
     *
     * @param roleId 角色ID
     * @return 菜单ID列表
     */

    public List<Long> getMenuIdList(Long roleId) {
        return sysRoleMenuMapper.selectList(
                Wrappers.<SysRoleMenuEntity>lambdaQuery().eq(SysRoleMenuEntity::getRoleId, roleId)
        ).stream().map(SysRoleMenuEntity::getMenuId).collect(Collectors.toList());
    }

    /**
     * 根据角色id集合删除 角色和菜单的关联关系
     *
     * @param idList 角色Id集合
     */
    public void deleteByRoleIdList(List<Long> idList) {
        remove(lambdaQuery().in(SysRoleMenuEntity::getRoleId, idList));
    }

    /**
     * 根据菜单删除 角色和菜单的 关联关系
     *
     * @param menuId 菜单ID
     */
    public void deleteByMenuId(Long menuId) {
        remove(new LambdaQueryWrapper<SysRoleMenuEntity>().eq(SysRoleMenuEntity::getMenuId, menuId));
    }
}
